<template>
  <div ref="imageWrapper">
    <a-card style="margin-bottom: 15px">
      <div class="table-page-search-wrapper">
        <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline" @keyup.enter.native="loadData">
          <a-row :gutter="24">
            <a-col :md="5" :sm="8">
              <a-form-model-item label="账套/核算单元" prop="accName">
                <a-input
                  @click.native="openOrganModel"
                  v-model="queryParam.accName"
                  readOnly
                  placeholder="请选择账套/核算单元"
                />
              </a-form-model-item>
            </a-col>
            <!-- <a-col :md="4" :sm="8">
              <a-form-model-item label="单位" prop="unitCode">
                <j-select-unit-info
                  v-model="queryParam.unitCode"
                  :trigger-change="true"
                  customReturnField="id"
                  :multi="false"
                ></j-select-unit-info>
              </a-form-model-item>
            </a-col> -->
            <a-col :md="4" :sm="8">
              <a-form-model-item label="年份" prop="accYear">
                <a-date-picker
                  mode="year"
                  format="yyyy"
                  value-format="yyyy"
                  v-model="queryParam.accYear"
                  :open="open"
                  @openChange="openChange"
                  @panelChange="panelChange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="8">
              <a-form-model-item label="分子科目" prop="moleculeSubject">
                <a-tree-select
                  v-model="queryParam.moleculeSubject"
                  tree-data-simple-mode
                  style="width: 220px"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择分子科目"
                  show-search
                  treeNodeFilterProp="title"
                  :tree-data="subjectTreeData"
                  allow-clear
                />
                <!-- <a-select allowClear placeholder="请选择科目" v-model="queryParam.subjects">
                  <a-select-option :value="item.value" v-for="item in subjectsList" :key="item.id">{{
                    item.label
                  }}</a-select-option>
                </a-select> -->
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="8">
              <a-form-model-item label="分母科目" prop="denominatorSubject">
                <a-tree-select
                  v-model="queryParam.denominatorSubject"
                  tree-data-simple-mode
                  style="width: 220px"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择分母科目"
                  show-search
                  treeNodeFilterProp="title"
                  :tree-data="subjectTreeData"
                  allow-clear
                />
                <!-- <a-select allowClear placeholder="请选择科目" v-model="queryParam.subjects">
                  <a-select-option :value="item.value" v-for="item in subjectsList" :key="item.id">{{
                    item.label
                  }}</a-select-option>
                </a-select> -->
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="8">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="loadData" icon="search">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">清除条件</a-button>
                <a-button
                  type="danger"
                  :loading="ydLoading"
                  @click="
                    () => {
                      if (this.tableData.length) {
                        const { accYear = '', moleculeSubject = '', denominatorSubject = '' } = this.queryParam
                        let ydnr = `【分子科目：${moleculeSubject}】【分母科目：${denominatorSubject}】`
                        let time = `【${accYear}】【科目比对分析】`
                        this.addYd(queryParam, ydnr, time)
                      } else {
                        this.$message.error('空数据不能新建疑点')
                      }
                    }
                  "
                  icon="arrow-right"
                  style="margin-left: 8px"
                  >转疑点</a-button
                >
              </span>
            </a-col>
            <a-col v-if="isBackButton" :offset="20" :md="4" :sm="8" style="text-align: right">
              <a-button type="primary" style="margin-left: 8px" @click="backUppage"> 返回 </a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-row :gutter="12">
      <a-col :md="24">
        <a-card>
          <div>
            <a-table
              :loading="loading"
              :columns="columns"
              bordered
              :pagination="false"
              :data-source="tableData"
              :scroll="{ x: 800, y: 500 }"
            ></a-table>
            <div v-if="panelShow" style="height: 370px; margin-top: 30px">
              <echarts :chartOpt="chartOpt" :istrigger="istrigger" />
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <YDModel ref="YDModel" :routerData="$route.path" />
    <CheckOrganModal ref="departModal" @ok="updateQueryParam"></CheckOrganModal>
  </div>
</template>

<script>
import echarts from '../components/echarts.vue'
import { Icon } from 'ant-design-vue'
import iconFont from '@/assets/font/iconfont'
import { getAction } from '@/api/manage'
import CheckOrganModal from '@/views/sj/sjxmzygl/yzzx/testcomponent/CheckOrganModal'
import { currentY } from '@/mixins/commontime.js'
import columns from './columns'
import lineChartOpt from './lineChartOpt'
import JSelectUnitInfo from '../JSelectUnitInfo'
import moment from 'moment'
import { base64toImg } from '@/mixins/base64toImg'
import YDModel from '@/views/sj/components/YDModel'
import { YzzxListMixin } from '../../yzzx/mixins/YzzxListMixin.js'
import jumpConfigMixin from '@/views/sj/sjxmzygl/sjxmss/jumpConfigMixin'
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFont,
})

export default {
  name: 'kmqsfx',
  components: {
    echarts,
    IconFont,
    JSelectUnitInfo,
    CheckOrganModal,
    YDModel,
  },
  mixins: [base64toImg, YzzxListMixin, jumpConfigMixin],
  watch: {
    $route: {
      handler: function (to) {
        if (Object.keys(to.query).length) {
          this.disableMixinCreated = true
          this.queryParam = Object.assign(this.queryParam, to.query)
          this.$nextTick(() => {
            this.loadData()
          })
        } else if (Object.keys(to.params).length && to.params.from == 'sjxmss') {
          let { accName, accId } = to.params
          this.queryParam.accName = accName
          this.queryParam.accCode = accId
          this.queryParam.moleculeSubject = '1001'
          this.queryParam.denominatorSubject = '1001'
          this.isBackButton = true
          let { endDate, startDate } = JSON.parse(to.params.returnRecord)
          this.queryParam.accYear = startDate && startDate.split('-')[0]
          this.returnRecord = to.params.returnRecord
          this.$nextTick(() => {
            this.loadData()
          })
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      moment,
      queryParam: {
        unitCode: '',
        accYear: currentY(),
        moleculeSubject: undefined,
        denominatorSubject: undefined,
        accName: '',
        accCode: '',
      },
      loading:false,
      isBackButton: false,
      panelShow: false,
      companyList: [],
      subjectsList2: [],
      subjectsList: [],
      subjectTreeData: [],
      month: [],
      columns,
      tableData: [],
      open: false,
      showTime: false,
      rules: {
        unitCode: [{ required: true, message: '请选择单位' }],
        accYear: [{ required: true, message: '请选择年份' }],
        moleculeSubject: [{ required: true, message: '请选择分子科目' }],
        denominatorSubject: [{ required: true, message: '请选择分母科目' }],
        accName: [{ required: true, message: '请选择账套' }],
      },
      url: {
        subjectTree: '/sjyzzx/sjZxzyAccountSubject/queryAllSubjectTree',
        objlist: '/sjkmfx/sjSubjectsAnalyse/queryFinanceSubjectCompare',
      },
      chartOpt: {
        id: 'lineChartOpt',
        options: lineChartOpt(),
      },
      istrigger: false,
    }
  },
  created() {
    this.getSubjectTree()
  },
  mounted() {
    this.$refs.ruleForm.resetFields()
  },
  methods: {
    updateQueryParam(data) {
      console.log(data, 'daat')
      let str1 = ''
      let str2 = ''
      data.map((item) => {
        // TODO 账套～～～
        str1 += item.accCode + ','
        str2 += item.accName + ','
      })
      if (str1.length > 0) {
        str1 = str1.substr(0, str1.length - 1)
      }
      if (str2.length > 0) {
        str2 = str2.substr(0, str2.length - 1)
      }
      this.queryParam.accCode = str1
      this.queryParam.accName = str2
    },
    openOrganModel() {
      this.$refs.departModal.edit()
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      var param = Object.assign(sqp, this.queryParam)
      return param
    },
    searchReset() {
      this.queryParam = this.$options.data().queryParam
      this.panelShow = false
      this.$refs.ruleForm.resetFields()
      this.tableData = []
      // this.loadData()
    },
    handleDatechange(dates) {
      this.queryParam.startMonth = dates[0]
      this.queryParam.endMonth = dates[1]
    },
    // // 查询
    loadData() {
      var params = this.queryParam //查询条件
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // this.getObjList(params)
          this.loading = true
          getAction(this.url.objlist, params).then((res) => {
            if (res.success === true && res.code === 200) {
              this.tableData = Object.assign([], res.result)
              let tempData = JSON.parse(JSON.stringify(res.result))
              this.chartOpt.options = lineChartOpt({
                accountData: this.mergeLineData(tempData, 'bl'),
                relativeData: this.mergeLineData(tempData, 'jz'),
              })
              this.panelShow = true
              this.istrigger = !this.istrigger
            } else {
              this.$message.error(res.message)
            }
          this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    mergeLineData(data, key) {
      let tmp = data.find((item) => item.id == key)
      const {
        jan = 0,
        feb = 0,
        mar = 0,
        apr = 0,
        may = 0,
        jun = 0,
        jul = 0,
        aug = 0,
        sept = 0,
        oct = 0,
        nov = 0,
        dec = 0,
      } = tmp
      return [jan, feb, mar, apr, may, jun, jul, aug, sept, oct, nov, dec]
    },
    // 弹出日历回调
    openChange(status) {
      if (status) {
        this.open = true
      } else {
        this.open = false
      }
    },
    // 日期面板变化
    panelChange(value) {
      this.open = false
      this.queryParam.accYear = moment(value).format('YYYY')
      this.$refs.ruleForm.validateField('accYear', (error) => {
        console.log(error)
      })
    },
  },
}
</script>
<style scoped>
.ant-select-dropdown {
  width: 220px;
}
</style>
<style lang="less" scoped>
@import '~@assets/less/common.less';
@import './index.less';
</style>